package com.wuda.servlet.user;
import com.wuda.bean.BookReview;
import com.wuda.dao.BookReviewDao;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
@WebServlet("/user/addBookReview")
public class AddBookReview extends HttpServlet {


	private final BookReviewDao bookReviewDao = new BookReviewDao();

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json; charset=utf8");

		int bookId = Integer.parseInt(req.getParameter("bookId"));
		int userId = Integer.parseInt(req.getParameter("userId"));
		int rating = Integer.parseInt(req.getParameter("rating"));
		String comment = req.getParameter("comment");


		// 准备返回参数
		int code = 500;
		String msg = "评论失败";

		BookReview bookReview = new BookReview();
		bookReview.setBookId(bookId);
		bookReview.setUserId(userId);
		bookReview.setRating(rating);
		bookReview.setComment(comment);
		//设置为当前时间
		bookReview.setReviewDate(new Date());

		System.out.println("接收到的新评论参数======>" + bookReview);

	    // 调用dao层添加评论
		boolean addSuccess = bookReviewDao.addBookReview(bookReview);

		if (addSuccess) {
			code = 200;
			msg = "添加成功";
		}

		// 返回JSON结果
		JSONObject jsonResult = new JSONObject();
		jsonResult.put("code", code);
		jsonResult.put("msg", msg);

		try (PrintWriter out = resp.getWriter()) {
			out.print(jsonResult);
			out.flush();
		}

	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

}

